package com.aduerr.v1shouyin.mvp.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.common.DatabaseManager;
import com.aduerr.v1shouyin.entity.LogoutEntity;
import com.aduerr.v1shouyin.entity.MemberConsumeDetailEntity;
import com.aduerr.v1shouyin.entity.MemberRechargeDetailEntity;
import com.aduerr.v1shouyin.entity.OrderGetPosOrderLEntity;
import com.aduerr.v1shouyin.entity.OrderRecordEntity;
import com.aduerr.v1shouyin.entity.PreAuthoOrderEntity;
import com.aduerr.v1shouyin.entity.ReportPosTotalEntity;
import com.aduerr.v1shouyin.entity.TransactionFlowEntity;
import com.aduerr.v1shouyin.entity.UserEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.print.PrinterWrapper;
import com.aduerr.v1shouyin.unioncard.BaseUnionActivity;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;
import com.yeahka.shouyintong.sdk.info.TradeInfo;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.internal.observers.BlockingBaseObserver;
import io.reactivex.schedulers.Schedulers;

public class SignOutActivity extends BaseUnionActivity {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_begintime)
    TextView tvBegintime;
    @BindView(R.id.tv_sellername)
    TextView tvSellername;
    @BindView(R.id.tv_shopname)
    TextView tvShopname;

    @BindView(R.id.tv_shihoujine)
    TextView tvShihoujine;
    @BindView(R.id.tv_ordermoney)
    TextView tvOrdermoney;
    @BindView(R.id.tv_refoundmoney)
    TextView tvRefoundmoney;
    @BindView(R.id.tv_shangjiayouhui)
    TextView tvShangjiayouhui;
    @BindView(R.id.tv_singout_print)
    TextView tvSingoutPrint;
    @BindView(R.id.tv_singout)
    TextView singout;

    private String netneedprambegintime;

    private String[] content = new String[34];
    private List<String> printcontent = new ArrayList<>();
    private Gson  gson;
    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sign_out;
    }

    @Override
    protected void initBase() {
        super.initView();
        ButterKnife.bind(this);
        tvTitle.setText("签退");
        initDateFromDateBase();
        gson = new Gson();
    }

    private void initDateFromDateBase() {
        //该收银员开始收银的时间
        netneedprambegintime = Hawk.get("sellbegintime");

        tvSellername.setText(Hawk.get("sellername"));
        tvShopname.setText(Hawk.get("shopname"));
        java.text.SimpleDateFormat sdFormatter = new java.text.SimpleDateFormat("yyyy" +
                "-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String sellendtime = sdFormatter.format(curDate);
        tvBegintime.setText(netneedprambegintime + "-" + sellendtime);
        initdate(netneedprambegintime, sellendtime);

    }


    @OnClick({R.id.img_back, R.id.tv_singout_print, R.id.tv_singout,
            R.id.tv_singout_order})
    public void onViewClicked(View view) {

        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_singout:
                beginPostNetForOut();
                break;
            case R.id.tv_singout_print:
                // TODO: 2017/12/14 0014  签退并打印
                Boolean hasShiftDuty = (Boolean) SharedPreferencesUtils.getParam(this,
                        "hasShiftDuty", true);
                @SuppressLint("SimpleDateFormat") java.text.SimpleDateFormat sdFormatter = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if(hasShiftDuty) {
                    //有交接班模式
                    Date logintime = Hawk.get("logintime");
                    Date curDate = new Date(System.currentTimeMillis());

                    try {
                        if(daysBetween(logintime, curDate) < 5) {//开始时间比结束时间小5天
                            //转化为具体的时间
                            String slogintime = sdFormatter.format(logintime);
                            String scurtime = sdFormatter.format(curDate);
                            //请求网络
                            initTotalData(slogintime, scurtime);
                        } else {
                            Calendar calendar = new GregorianCalendar();
                            calendar.setTime(logintime);
                            calendar.add(calendar.DATE, 5);//把日期往后加5天，若想把日期向后推一天则将负数改为正数
                            curDate = calendar.getTime();
                            //转化为开始时间和开始时间加5天
                            String slogintime = sdFormatter.format(logintime);
                            String scurtime = sdFormatter.format(curDate);
                            //请求网络
                            initTotalData(slogintime, scurtime);
                        }
                    } catch(ParseException e) {
                        e.printStackTrace();
                    }


                } else {
                    //无交接班模式
                    Date curDate = new Date(System.currentTimeMillis());
                    String endtime = sdFormatter.format(curDate);
                    String[] split = endtime.split(" ");
                    initTotalData(split[0] + " 00:00:00", endtime);
                }
                //==================================
                break;
            case R.id.tv_singout_order:
                singOutWithPrintTurnover();
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
//                                R.drawable.print_public);
//                        if(bitmap != null) {
//                            List<OrderRecordEntity> list = null;
//                            Boolean hasShiftDuty =
//                                    (Boolean) SharedPreferencesUtils.getParam
//                                    (SignOutActivity.this, "hasShiftDuty", true);
//                            if(hasShiftDuty) {
//                                list = DatabaseManager.getInstance().getQueryAll
//                                (OrderRecordEntity.class);
//                            } else { //无交接版模式，但现在的签退逻辑用不到，功能先保留
//                                SimpleDateFormat sdf = new SimpleDateFormat
//                                ("yyyy-MM-dd" +
//                                        " HH:mm:ss");
//                                Date curDate = new Date(System.currentTimeMillis());
//                                String endtime = sdf.format(curDate);
//                                String[] split = endtime.split(" ");
//                                list = DatabaseManager.getInstance()
//                                .getQueryByCondition(OrderRecordEntity.class,
//                                "payTime", split[0] + " 00:00:00", endtime);
//                            }
//                            if(list.size() == 0) {
//                                showDialog();
//                                return;
//                            }
//                            for(int i = 0; i < list.size(); i++) {
//                                OrderRecordEntity order = list.get(i);
//                                switch(order.getType()) {
//                                    case 1://支付宝
//                                        content[11] =
//                                                getResources().getString(R.string
//                                                .text_dingdan_zhifubao);
//                                        bitmap =
//                                                BitmapFactory.decodeResource
//                                                (getResources(), R.drawable.print_z);
//                                        content[0] = order.getOrderMoney();
//                                        content[4] = order.getCustomer();
//                                        content[5] = order.getPayTime();
//                                        content[6] = order.getOrderId();
//                                        content[8] = order.getShopName();
//                                        content[9] = order.getCashier();
//                                        content[10] = order.getRemarks();
//                                        content[12] = order.getOrderState();
//                                        content[13] = order.getMerchantName();
//
//
//
//                                        print(bitmap, content,
//                                                Constants.PRINT_ORDER_DETAIL, 1);
//                                        break;
//                                    case 2://微信
//                                        content[11] =
//                                                getResources().getString(R.string
//                                                .text_dingdan_weixin);
//                                        bitmap =
//                                                BitmapFactory.decodeResource
//                                                (getResources(), R.drawable.print_w);
//                                        content[0] = order.getOrderMoney();
//                                        content[4] = order.getCustomer();
//                                        content[5] = order.getPayTime();
//                                        content[6] = order.getOrderId();
//                                        content[8] = order.getShopName();
//                                        content[9] = order.getCashier();
//                                        content[10] = order.getRemarks();
//                                        content[12] = order.getOrderState();
//                                        content[13] = order.getMerchantName();
//                                        print(bitmap, content,
//                                                Constants.PRINT_ORDER_DETAIL, 1);
//                                        break;
//                                    case 3://会员充值
//                                        content[14] = order.getOrderId();
//                                        content[10] = order.getMerchantName();
//                                        content[8] = order.getRechargeType();
//                                        content[2] = order.getOrderMoney();
//                                        content[15] = order.getSendMoney();
//                                        content[13] = order.getBalance();
//                                        content[3] = order.getCustomer();
//                                        content[4] = order.getPhone();
//                                        content[5] = order.getDiscount();
//                                        content[7] = order.getIntegral();
//                                        content[11] = order.getPayTime();
//                                        content[0] = order.getShopName();
//                                        content[9] = order.getCashier();
//                                        content[12] = order.getRemarks();
//                                        print(null, content,
//                                                Constants.PRINT_MEMBER_RECHARGE_2, 1);
//                                        break;
//                                    case 4://会员消费
//                                        content[0] = "会员消费";
//                                        content[14] = order.getOrderId();
//                                        content[10] = order.getMerchantName();
//                                        content[1] = order.getOrderMoney();
//                                        content[13] = order.getBalance();
//                                        content[5] = order.getCustomer();
//                                        content[3] = order.getPhone();
//                                        content[6] = order.getIntegral();
//                                        content[11] = order.getPayTime();
//                                        content[9] = order.getShopName();
//                                        content[8] = order.getCashier();
//                                        content[12] = order.getRemarks();
//                                        print(null, content,
//                                                Constants
//                                                .PRINT_MEMBER_CONSUME_RESULT, 1);
//                                        break;
//                                    case 5://刷卡消费
//                                        break;
//                                    case 12://消费撤销
//                                        break;
////                                    case 6://预授权法
////                                    case 7://预授权撤销
////                                    case 8://预授权完成
////                                    case 9://预授权完成撤销
//                                    case 10://支付宝退款
//                                    case 11://微信退款
//                                        if(order.getType() == 10) {
//                                            bitmap =
//                                                    BitmapFactory.decodeResource
//                                                    (SignOutActivity.this
//                                                    .getResources(), R.drawable
//                                                    .print_z_refound);
//                                        } else if(order.getType() == 11) {
//                                            bitmap =
//                                                    BitmapFactory.decodeResource
//                                                    (SignOutActivity.this
//                                                    .getResources(), R.drawable
//                                                    .print_w_refound);
//                                        }
//                                        if(bitmap != null) {
//                                            content[14] = order.getMerchantName();
//                                            content[6] = order.getOrderId();
//                                            content[0] = order.getOrderMoney();
//                                            content[12] = order.getRefundMoney();
//                                            content[11] = order.getRefundTime();
//                                            content[8] = order.getShopName();
//                                            content[9] = order.getCashier();
//                                            content[13] = order.getCustomer();
//                                            content[5] = order.getPayTime();
//                                            content[10] = order.getRemarks();
//                                            content[15] = order.getRefundRemarks();
//                                            print(bitmap, content,
//                                                    Constants.PRINT_REFUND_RESULT_ORDER
//                                                    , 1);
//                                        }
//                                        break;
//                                    case 13:
//                                        content[0] = "现金收款";
//                                        content[1] = order.getOrderId();
//                                        content[3] = order.getOrderMoney();
//                                        content[4] = order.getMerchantName();
//                                        content[5] = order.getCashier();
//                                        content[6] = order.getShopName();
//                                        content[7] = order.getPayTime();
//                                        content[8] = order.getRemarks();
//                                        print(null, content, Constants.PRINT_CASH_ORDER
//                                                , 1);
//                                        break;
//                                    case 14:
//                                    case 15:
//                                    case 16:
//                                    case 17:
//                                        PreAuthoOrderEntity.DataBean dataBean =
//                                                new PreAuthoOrderEntity.DataBean();
//                                        dataBean.setConsumeMoney(order
//                                        .getmConsumeMoney());
//                                        dataBean.setRefundRemark(order
//                                        .getmConsumeRemark());
//                                        dataBean.setRefundTime(order.getmConsumeTime());
//                                        dataBean.setConsumeTime(order.getmConsumeTime
//                                        ());
//                                        dataBean.setCreateTime(order.getmCreateTime());
//                                        dataBean.setDepositMoney(order
//                                        .getmDepositMoney());
//                                        dataBean.setGoodsMoney(order.getmGoodsMoney());
//                                        dataBean.setOrderID(order.getmOrderID());
//                                        dataBean.setOrderState(order.getmOrderState());
//                                        dataBean.setPayTime(order.getmPayTime());
//                                        dataBean.setPayType(order.getmPayType());
//                                        dataBean.setRefundRemark(order
//                                        .getmRefundRemark());
//                                        dataBean.setRefundTime(order.getmRefundTime());
//                                        dataBean.setRefundUserID(order
//                                        .getmRefundUserID());
//                                        dataBean.setRefundUserName(order
//                                        .getmRefundUserName());
//                                        dataBean.setShopID(order.getmShopID());
//                                        dataBean.setShopName(order.getmShopName());
//                                        dataBean.setSiteUserID(order.getmSiteUserID());
//                                        dataBean.setSiteUserName(order
//                                        .getmSiteUserName());
//                                        dataBean.setTransactionID(order
//                                        .getmTransactionID());
//                                        dataBean.setConsumeUserName(order
//                                        .getmConsumeUserName());
//                                        dataBean.setCreateRemark(order
//                                        .getmCreateRemark());
//                                        if(order.getmOrderState() == 1) {
//                                            printPreAutho(dataBean,
//                                                    Constants.PRINT_PRE_AUTHO_01, 1);
//                                        } else if(order.getmOrderState() == 2) {
//                                            printPreAutho(dataBean,
//                                                    Constants.PRINT_PRE_AUTHO_02, 1);
//                                        } else if(order.getmOrderState() == 3) {
//                                            printPreAutho(dataBean,
//                                                    Constants.PRINT_PRE_AUTHO_03, 1);
//                                        } else if(order.getmOrderState() == 4) {
//                                            printPreAutho(dataBean,
//                                                    Constants.PRINT_PRE_AUTHO_04, 1);
//                                        }
//                                        break;
//                                }
//                                if(i == list.size() - 1) {
//                                    beginPostNetForOut();
//                                }
//                            }
//                        }
//                    }
//                }).start();
                break;
        }
    }

    private void initTotalData(String begintime, String endtime) {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("begintime", begintime);
        addParams.put("endtime", endtime);
        APIRetrofit.getAPIService().getReportPosTotal(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<ReportPosTotalEntity>() {
                    @Override
                    public void onNext(ReportPosTotalEntity reportPosTotalEntity) {
                        //                    if (Tools.isAvailable
                        //                    (reportPosTotalEntity))return;
                        int success = reportPosTotalEntity.getSuccess();
                        if(success == 1) {
                            ReportPosTotalEntity.DataBean data =
                                    reportPosTotalEntity.getData();
                            if(data != null) {


                                printcontent.add("开始时间" + begintime);
                                printcontent.add("结束时间" + endtime);
                                printcontent.add("--------------------------");
                                printcontent.add("类   型      笔数   总金额");
                                if(!(data.getOrdercount()).equals("0")) {
                                    printcontent.add("订   单:      " + data.getOrdercount() + "     " + data.getOrdermoney());
                                }
                                //现金
                                if(!(data.getCashcount()).equals("0")) {
                                    printcontent.add("现金收款:     " + data.getCashcount() + "     " + data.getCashmoney());
                                }

                                if(!(data.getAlipaycount()).equals("0")) {
                                    printcontent.add("支付宝收款:   " + data.getAlipaycount() + "     " + data.getAlipaymoney());
                                }
                                if(!(data.getWxcount()).equals("0")) {
                                    printcontent.add("微信收款:     " + data.getWxcount() + "     " + data.getWxmoney());
                                }
                                if(!(data.getWxcount()).equals("0")) {
                                    printcontent.add("云闪付收款:   " + data.getYsfcount() + "     " + data.getYsfmoney());
                                }

                                if(!"0".equals((data.getDccoun()))) {
                                    printcontent.add("数币收款:       " + (data.getDccoun() == null?0:data.getDccoun())
                                            + "     " + (data.getDcmone() == null?0:data.getDcmone()));
                                }

                                if(!(data.getMemberexcount()).equals("0")) {
                                    printcontent.add("储值卡消费:   " + data.getMemberexcount() + "     " + data.getMemberexmoney());
                                }

                                if(!(data.getMemberupcount()).equals("0")) {
                                    printcontent.add("会员充值:     " + data.getMemberupcount() + "     " + data.getMemberupmoney());
                                }


                                if(!(data.getOrdercount()).equals("0")) {
                                    printcontent.add("商家实收:     " + data.getOrdercount() + "     " + data.getShishoumoney());
                                }

                                if(!(data.getSelleryouhuicount()).equals("0")) {
                                    printcontent.add("商家优惠:     " + data.getSelleryouhuicount() + "     " + data.getSelleryouhuimoney());
                                }
                                if(!(data.getYouhuicount()).equals("0")) {
                                    printcontent.add("官方优惠:     " + data.getYouhuicount() + "     " + data.getYouhuimoney());
                                }
                                //卡券使用数量
                                if(!(data.getCardusedcount()).equals("0")) {
                                    printcontent.add("核销金额:     " + data.getCardusedcount() + "     " + data.getCardusedmoney());
                                }

                                if(!(data.getSmysqcount()).equals("0")) {
                                    printcontent.add("扫码预授权:   " + data.getSmysqcount() + "     " + data.getSmysqmoney());
                                }

                                if(!(data.getTodaycount()).equals("0")) {
                                    printcontent.add("今日退款:     " + data.getTodaycount() + "     " + data.getTodaymoney());
                                }
                                if(!(data.getYestodaycount()).equals("0")) {
                                    printcontent.add("昨日退款:     " + data.getYestodaycount() + "     " + data.getYestodaymoney());
                                }

                                if(!(data.getYinliancount()).equals("0")) {
                                    printcontent.add("银联收款:     " + data.getYinliancount() + "     " + data.getYinlianmoney());
                                }
                                if(!(data.getYinliandaijicount()).equals("0")) {
                                    printcontent.add("银联贷记收款:  " + data.getYinliandaijicount() + "     " + data.getYinliandaijimoney());
                                }
                                if(!(data.getYinlianjiejicount()).equals("0")) {
                                    printcontent.add("银联借记收款:  " + data.getYinlianjiejicount() + "     " + data.getYinliandaijimoney());
                                }
                                if(!(data.getYinlianrefundcount()).equals("0")) {
                                    printcontent.add("银联退款:     " + data.getYinlianrefundcount() + "     " + data.getYinlianrefundmoney());
                                }
                                //将极光推送的别名重置.
                                JPushInterface.setAlias(App.getApp(), "",
                                        (i, s, set) -> Log.d("alias", "set alias result" +
                                                " is" + i));
                                //打印相关的信息
//                                int printpage = (int) SharedPreferencesUtils.getParam
//                                (SignOutActivity.this, "printpage", 1);
//                                if (printpage == 0) {
//                                    ToastUtils.showToast(SignOutActivity.this,
//                                    "打印张数设置为不打印,本次签退不会出小票");
//                                    beginPostNetForOut();//签退
//                                    return;
//                                }
                                Bitmap bitmap =
                                        BitmapFactory.decodeResource(getResources(),
                                                R.drawable.print_public);
                                if(bitmap != null) {
                                    printSignOut(bitmap, printcontent);
                                }
                                beginPostNetForOut();

                            }

                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            startActivity(new Intent(SignOutActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(reportPosTotalEntity.getErrMsg());
                            SharedPreferencesUtils.remove(SignOutActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(SignOutActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(SignOutActivity.this,
                                    LoginActivity.class));
                            finish();
                        } else {
                            ToastUtils.showToast(SignOutActivity.this,
                                    reportPosTotalEntity.getErrMsg() + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(App.getApp(), "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(App.getApp(), "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(App.getApp(), "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void printSignOut(Bitmap logo, List<String> printcontent) {

        printSignOutDetail(logo, printcontent);
    }

    private void printSignOutDetail(Bitmap logo, List<String> printcontent) {
        PrinterWrapper.printSignOut(logo, printcontent);
    }

    private void print(Bitmap logo, String[] content, int orderType, int printPage) {
        printOrder(logo, content, orderType, printPage);
    }

    private void printOrder(Bitmap logo, String[] content, int orderType, int printPage) {
        PrinterWrapper.printPosOrder(logo, content, orderType, printPage);
    }

    private void printPreAutho(PreAuthoOrderEntity.DataBean dataBean, int orderType,
                               int printPage) {
        printPreAuthoOrder(dataBean, orderType, printPage);
    }

    private void printPreAuthoOrder(PreAuthoOrderEntity.DataBean dataBean, int orderType, int printPage) {
        PrinterWrapper.printPreAuthoOrder(dataBean, orderType, printPage,false);
    }

    private void printUnion(TradeInfo tradeInfo) {
        printUnionDetail(tradeInfo);
    }

    void printUnionDetail(TradeInfo tradeInfo) {
        PrinterWrapper.printUnionOrder(BitmapFactory.decodeResource(getResources(),
                R.drawable.print_union), tradeInfo);
    }


    //收银员收银时间段内的数据
    private void initdate(String begintime, String endtime) {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("beginTime", begintime);
        addParams.put("endTime", endtime);
        APIRetrofit.getAPIService().getLogoutReport(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<LogoutEntity>() {
                    @Override
                    public void onNext(LogoutEntity logoutEntity) {
                        //                    if (Tools.isAvailable(logoutEntity)) return;
                        int success = logoutEntity.getSuccess();
                        if(success == 1) {
//                            content[1] = reportPosTotalEntity.getPayMoney() + "";
//                            content[2] = reportPosTotalEntity.getOrderMoney() + "";
//                            content[3] = reportPosTotalEntity.getRefundMoney() + "";
//                            content[4] = reportPosTotalEntity.getSellerDiscount() + "";
//                            content[5] = Hawk.get("sellername");
//                            content[6] = Hawk.get("shopname");
//                            content[7] = Hawk.get("sellbegintime");

                            tvShihoujine.setText(logoutEntity.getPayMoney() + "");
                            tvOrdermoney.setText(logoutEntity.getOrderMoney() + "");
                            tvRefoundmoney.setText(logoutEntity.getRefundMoney() + "");
                            tvShangjiayouhui.setText(logoutEntity.getSellerDiscount() + "");
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            startActivity(new Intent(SignOutActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(logoutEntity.getErrMsg());
                            SharedPreferencesUtils.remove(SignOutActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(SignOutActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(SignOutActivity.this,
                                    LoginActivity.class));
                            finish();
                        } else {
                            ToastUtils.showToast(SignOutActivity.this,
                                    logoutEntity.getErrMsg() + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(App.getApp(), "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(App.getApp(), "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(App.getApp(), "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }
                });


    }

    public void beginPostNetForOut() {
        postNetforLogin(Hawk.get("userName"), Hawk.get("password"));
    }

    /**
     * 请求成功=1
     * 签名无效=-1
     * 密码错误=-2
     * 用户不存在=-3
     * 异常错误=-4
     * 用户已暂停使用=-6
     * 设置未注册=-100
     * 设备未绑定=-200
     * 登陆信息错误=-300
     */
    private void postNetforLogin(String account, String password_content) {
//        ToastUtils.showToast(this, "登录结果展示");
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("userName", "" + account);
        addParams.put("password", "" + password_content);
        addParams.put("logType", "1");
//        addParams.put("logType", Hawk.get("LogID"));
        APIRetrofit.getAPIService().Signout(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<UserEntity>() {
                    @Override
                    public void onNext(UserEntity userEntity) {
                        //                    if (Tools.isAvailable(userEntity))return;
                        int success = userEntity.getSuccess();
                        if(success == 1) {
                            //将数据存入数据库tv_singout
                            SharedPreferencesUtils.remove(SignOutActivity.this,
                                    "autologin");
//                            SharedPreferencesUtils.remove(SignOutActivity.this,
//                            "remberpassword");
                            //删除所有本地的交易记录
                            DatabaseManager.getInstance().deleteAll(OrderRecordEntity.class);
                            DatabaseManager.getInstance().deleteAll(TransactionFlowEntity.class);
                            //将极光推送的别名重置.
                            JPushInterface.setAlias(App.getApp(), "",
                                    (i, s, set) -> Log.d("alias",
                                            "set alias result is" + i));
                            Intent intent = new Intent(SignOutActivity.this,
                                    LoginActivity.class);
                            startActivity(intent);
                            finish();
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(SignOutActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(SignOutActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(SignOutActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            SharedPreferencesUtils.remove(SignOutActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(SignOutActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(SignOutActivity.this,
                                    LoginActivity.class));
                            finish();
                        } else {
                            ToastUtils.showToast(SignOutActivity.this,
                                    userEntity.getErrMsg() + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(App.getApp(), "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(App.getApp(), "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(App.getApp(), "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }


    private void showDialog() {
        AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(SignOutActivity.this);
        normalDialog.setTitle("提示");
        normalDialog.setMessage("暂无交易流水，确定签退吗?");
        normalDialog.setPositiveButton("确定",
                (dialog, which) -> {
                    beginPostNetForOut();
                });
        normalDialog.setNegativeButton("取消",
                (dialog, which) -> {
                    //...To-do
                });
        // 显示
        normalDialog.show();
    }


    public void singOutWithPrintTurnover() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<TransactionFlowEntity> list = null;
                Boolean hasShiftDuty =
                        (Boolean) SharedPreferencesUtils.getParam(SignOutActivity.this,
                                "hasShiftDuty", true);
                if(hasShiftDuty) {
                    list = DatabaseManager.getInstance().getQueryAll(TransactionFlowEntity.class);
                } else { //无交接版模式，但现在的签退逻辑用不到，功能先保留
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd" +
                            " HH:mm:ss");
                    Date curDate = new Date(System.currentTimeMillis());
                    String endtime = sdf.format(curDate);
                    String[] split = endtime.split(" ");
                    list = DatabaseManager.getInstance().getQueryByCondition(TransactionFlowEntity.class, "payTime", split[0] + " 00:00:00", endtime);
                }
                if(list ==null || list.size() == 0) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showDialog();
                        }
                    });

                    return;
                }

                for(int i = 0; i < list.size(); i++) {
                    switch(list.get(i).getPrintType()) {
                        case 1:
                            String json1 = list.get(i).getJson();
                            printOrderTurnover(json1);
                            break;

                            //1,普通收款  2， 会员消费  3,会员充值   4，预授权冻结 5,预授权完成  6，预授权撤销，7，预授权完成撤销  8 核销  10 退款
                        case 2:
                            String json2 = list.get(i).getJson();
                            printVipConsumeTurnover(json2);
                            break;

                        case 3:
                            String json3 = list.get(i).getJson();
                            printVipRechargeTurnover(json3);
                            break;

                        case 4:
                            String json4 = list.get(i).getJson();
                            printPreAuth01(json4);
                            break;

                        case 5:
                            String json5 = list.get(i).getJson();
                            printPreAuth02(json5);
                            break;

                        case 6:
                            String json6 = list.get(i).getJson();
                            printPreAuth03(json6);
                            break;


                        case 7:
                            String json7 = list.get(i).getJson();
                            printPreAuth04(json7);
                            break;

                        case 8:
                            String json8 = list.get(i).getJson();
                            printHxTurnover(json8);
                            break;
                        case 10:
                            String json10 = list.get(i).getJson();
                            printRefund(json10);

                            break;
                        case 11:
                            String json11 = list.get(i).getJson();
                            printJPushOrder(json11);
                            break;

                    }
                     if(i==list.size()-1){
                         beginPostNetForOut();
                     }
                }

            }
        }).start();
    }


    /**
     * 打印收款和退款订单流水
     */
    public void printOrderTurnover(String json) {
        content = new String[20];
        OrderGetPosOrderLEntity.DataBean.ListBean data = gson.fromJson(json,OrderGetPosOrderLEntity.DataBean.ListBean.class);
        content[0] = data.getOrderid();//订单编号
        content[1] = data.getShopname();//门店
        content[2] = data.getSiteusername();//收银员
        content[3] = data.getPaytype();//支付方式
        content[4] = data.getPaystate();//支付状态
        content[5] = data.getPaytime();//支付时间
        content[6] = data.getOrdermoney();//订单金额
        content[7] = data.getRealpay();//实收金额
        content[8] = data.getRefund();//退款金额
        content[9] = data.getOrdernote();//订单备注
        content[10] = data.getRefundreason();//退款备注
        content[11] = data.getRefundtime();//退款时间
        content[12] = Hawk.get("company");//账号公司
        content[13] = data.getUseraccount();//用户账号 不一定存在
        content[14] = data.getOutorderid();//不一定存在
        content[15] = data.getSelleryouhui();//不一定存在
        content[16] = data.getYouhui();//不一定存在

        if(data.getPaystate().equals("已付款")){
            PrinterWrapper.printNewOrder(1, false, content);
        }else{
            PrinterWrapper.printNewRefundOrder(1, false, content);
        }

    }

    /**
     * 打印会员消费流水
     */
    public void printVipConsumeTurnover(String json) {
        MemberConsumeDetailEntity.DataBean  dataBean  = gson.fromJson(json,MemberConsumeDetailEntity.DataBean.class);
        if(dataBean != null){
            PrinterWrapper.printNewMemberConsume(1,dataBean,false);
        }
    }

    /**
     * 打印会员充值流水
     */
    public void printVipRechargeTurnover(String json) {
        MemberRechargeDetailEntity.DataBean  dataBean  = gson.fromJson(json,MemberRechargeDetailEntity.DataBean.class);
        if(dataBean != null){
            PrinterWrapper.printNewMemberRecharge(1,dataBean,false);
        }
    }

    /**
     * 预授权冻资中
     */
    public void printPreAuth01(String json){
        PreAuthoOrderEntity.DataBean dataBean  = gson.fromJson(json,PreAuthoOrderEntity.DataBean.class);
        if(dataBean != null){
            PrinterWrapper.printPreAuthoOrder(dataBean,Constants.PRINT_PRE_AUTHO_01,1,false);
        }
    }

    /**
     * 预授权完成
     */
    public void printPreAuth02(String json){
        PreAuthoOrderEntity.DataBean dataBean  = gson.fromJson(json,PreAuthoOrderEntity.DataBean.class);
        if(dataBean != null){
            PrinterWrapper.printPreAuthoOrder(dataBean,Constants.PRINT_PRE_AUTHO_02,1,false);
        }
    }


    /**
     * 预授权撤销
     */
    public void printPreAuth03(String json){
        PreAuthoOrderEntity.DataBean dataBean  = gson.fromJson(json,PreAuthoOrderEntity.DataBean.class);
        if(dataBean != null){
            PrinterWrapper.printPreAuthoOrder(dataBean,Constants.PRINT_PRE_AUTHO_03,1,false);
        }
    }
    /**
     * 预授权完成撤销
     */
    public void printPreAuth04(String json){
        PreAuthoOrderEntity.DataBean dataBean  = gson.fromJson(json,PreAuthoOrderEntity.DataBean.class);
        if(dataBean != null){
            PrinterWrapper.printPreAuthoOrder(dataBean,Constants.PRINT_PRE_AUTHO_04,1,false);
        }
    }

    public void printHxTurnover(String json) {
        String[] content = new String[]{};
        content = gson.fromJson(json, content.getClass());
        if(content != null) {
            PrinterWrapper.printHxDetail(1,false,content);

        }
    }

    public void printRefund(String json) {
        String[] content = new String[]{};
        content = gson.fromJson(json, content.getClass());
        if(content != null) {
            PrinterWrapper.printNewRefundOrder(1,false,content);
        }
    }


    public void printJPushOrder(String json) {
        String[] content = new String[]{};
        content = gson.fromJson(json, content.getClass());
        if(content != null) {
            PrinterWrapper.printJPushOrderDetail(false, content, 1);
        }
    }

}
